"""
主题: 使用装饰器扩充类的功能
问题: 你想通过反省或者重写类定义的某部分来修改它的行为，但是你又不希望使用继承或元类的方式。
提示 : 
"""

def log_getattribute(cls):
    # Get the original implementation
    orig_getattribute = cls.__getattribute__

    # Make a new definition
    def new_getattribute(self, name):
        print('getting:', name)
        return orig_getattribute(self, name)

    # Attach to the class and return
    cls.__getattribute__ = new_getattribute
    return cls


# Example use
@log_getattribute
class A:
    def __init__(self, x):
        self.x = x

    def spam(self):
        print("spam")

''' 使用到继承实现 '''

class LoggedGetattribute:
    def __getattribute__(self, name):
        print('getting:', name)
        return super().__getattribute__(name)

# Example:
class A1(LoggedGetattribute):
    def __init__(self,x):
        self.x = x
    def spam(self):
        print("spam")

def recipe1():
    a = A(42)
    print(f"{a.x = }")
    print(f"{a.spam() = }")

def recipe2():
    a = A1(42)
    print(f"{a.x = }")
    print(f"{a.spam() = }")

def main():
    print('recipe1'.center(20, '*'))
    recipe1()
    print('recipe2'.center(20, '*'))
    recipe2()

if __name__ == '__main__':
    main()           